package com.ytjj.qmyx.mall.utils;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.ITemplate;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.notify.Notify;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.dto.GtReq;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.StartActivityTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * unipush 推送
 */
@Component
public class GtPushUtil {

    @Value("${quanmingyanxuan.gtPush.appId}")
    private String appId;
    @Value("${quanmingyanxuan.gtPush.appKey}")
    private String appKey;
    @Value("${quanmingyanxuan.gtPush.masterSecret}")
    private String masterSecret;
    @Value("${quanmingyanxuan.gtPush.url}")
    private String url;

    /**
     * 根据cid单推
     * @param cid
     * @return
     */
    public  Map<String, Object> pushMessage(String cid,Map<String,Object> param) {
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        // 使用透传模板
        ITemplate iTemplate = this.buildTransmissionTemplate(param);
        SingleMessage message = new SingleMessage();
        message.setData(iTemplate);
        // 设置消息离线
        message.setOffline(true);
        // 离线消息有效时间为7天
        message.setOfflineExpireTime(1000 * 3600 * 24 * 7);
        //添加要推送的终端
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        IPushResult result;
        Map<String, Object> response = null;
        // 执行推送
        try {
            result = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            result = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (result != null) {
            response = result.getResponse();
        }
        return response;
    }

    /**
     * 根据cid批量推
     * @param cids
     * @param param
     */
    public IPushResult pushToList(List<String> cids, Map<String,Object> param) {
        // 配置返回每个用户返回用户状态，可选
        System.setProperty("gexin_pushList_needDetails", "true");
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        // 透传模板
        ITemplate template = this.buildTransmissionTemplate(param);
        ListMessage message = new ListMessage();
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 配置推送目标
        List<Target> targets = new ArrayList<Target>();
        Target target = null;
        for (String cid : cids) {
            target = new Target();
            target.setAppId(appId);
            target.setClientId(cid);
            targets.add(target);
        }
        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);
        IPushResult ret = push.pushMessageToList(taskId, targets);
        return ret;
    }

    /**
     * 群推
     * @param param
     */
    public  IPushResult pushToApp(Map<String,Object> param) {
        // 配置返回每个用户返回用户状态，可选
        System.setProperty("gexin_pushList_needDetails", "true");
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        // 透传模板
        ITemplate template = this.buildTransmissionTemplate(param);
        AppMessage message = new AppMessage();
        // 设置appid
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);
        // 设置模板
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        // 离线有效时间，单位为毫秒
        message.setOfflineExpireTime(24 * 1000 * 3600);
        IPushResult ret = push.pushMessageToApp(message);
        return ret;
    }

    /**
     * 透传模板
     * @param param
     * @return
     */
    private ITemplate buildTransmissionTemplate(Map<String,Object> param) {
        // 标题、内容、显示图片、跳转图片
        String title = param.get("title").toString();
        String content = param.get("content").toString();
        // String icon = param.get("icon").toString();
        String skipUrl = param.get("url").toString();

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 内容
        template.setTransmissionContent(JSONObject.toJSONString(param));
        template.setTransmissionType(2); // 这个Type为int型，填写1则自动启动app

        String intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=com.aysd.bcfa/io.dcloud.PandoraEntry;" +
                "S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+skipUrl+";end";
        Notify notify = new Notify();
        // 通知栏显示标题
        notify.setTitle(title);
        // 通知栏内容
        notify.setContent(content);
        notify.setIntent(intent);
        notify.setType(GtReq.NotifyInfo.Type._intent);
        // 设置第三方通知
        template.set3rdNotifyInfo(notify);
        // ios 配置
        template.setAPNInfo(getAPNPayload(skipUrl,title,content));
        return template;
    }

    /**
     * 通知模板(打开应用内页面)
     * @param param
     * @return
     */
    private ITemplate buildStartActivityTemplate(Map<String,Object> param){
        // 标题、内容、显示图片、跳转图片
        String title = param.get("title").toString();
        String content = param.get("content").toString();
        // String icon = param.get("icon").toString();
        String skipUrl = param.get("url").toString();

        StartActivityTemplate template = new StartActivityTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(content);
        // 配置通知栏图标
        style.setLogo("");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

        String intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=com.aysd.bcfa/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+skipUrl+";end";
        template.setIntent(intent); //最大长度限制为1000
        template.setAPNInfo(getAPNPayload(skipUrl,title,content)); //详见本页iOS通知样式设置
        return template;

    }

    private static APNPayload getAPNPayload(String skipUrl, String title, String content) {
        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        payload.setAutoBadge("+1");
        payload.setContentAvailable(0);
        payload.setSound("default");
        payload.addCustomMsg("url",skipUrl);
        payload.setAlertMsg(getDictionaryAlertMsg(title,content));
        return payload;
    }

    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String content) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(content);
        // iOS8.2以上版本支持
        alertMsg.setTitle(title);
        return alertMsg;
    }

}
